package com.st;

import android.os.*;
import android.util.*;
import android.widget.*;
import org.apache.http.*;
import org.apache.http.client.*;
import org.apache.http.client.methods.*;
import org.apache.http.entity.*;
import org.apache.http.impl.client.*;
import org.apache.http.params.*;
import org.apache.http.util.*;
import support.*;

import java.io.*;
import java.util.*;

/**
 * This class connects to the DataPingServlet and sends a hashtable of <string, string> and gets a
 * hashtable of <{@link DataKeys}, serializable>.
 * The userid and password are sent to the servlet.
 * The userid, password, and picture are downloaded from the servlet.
 *
 * @author Nazmul Idris
 * @version 1.0
 * @since May 17, 2008, 6:46:41 PM
 */
public class GetDataFromWebService {

// service urls

// this is loopback interface for localhost - 10.0.2.2
public static final String LoginServiceUri = "http://10.0.2.2:9090/Service/ping";
int NetworkConnectionTimeout_ms = 5000;


// data


/** ref to the calling activity */
private static NetworkActivity _activity;
private String uid;
private String pwd;
private ByteBuffer data;
private Exception ex;
private Hashtable<DataKeys, Serializable> dataFromServlet;


// methods


public void execute(NetworkActivity activity) {

  _activity = activity;

  uid = activity.ttfUserid.getText().toString();
  pwd = activity.ttfPassword.getText().toString();

  // allows non-"edt" thread to be re-inserted into the "edt" queue
  final Handler uiThreadCallback = new Handler();

  // performs rendering in the "edt" thread, after background operation is complete
  final Runnable runInUIThread = new Runnable() {
    public void run() {
      _showInUI();
    }
  };

  new Thread() {
    @Override public void run() {
      _doInBackgroundPost();
      uiThreadCallback.post(runInUIThread);
    }
  }.start();

  Toast.makeText(_activity,
                 "Getting data from servlet",
                 Toast.LENGTH_LONG).show();

}

/** this method is called in a non-"edt" thread */
private void _doInBackgroundPost() {
  Log.i(getClass().getSimpleName(), "background task - start");

  Hashtable<String, String> map = new Hashtable();
  map.put("uid", uid);
  map.put("pwd", pwd);

  try {
    HttpParams params = new BasicHttpParams();

    // set params for connection...
    HttpConnectionParams.setStaleCheckingEnabled(params, false);
    HttpConnectionParams.setConnectionTimeout(params, NetworkConnectionTimeout_ms);
    HttpConnectionParams.setSoTimeout(params, NetworkConnectionTimeout_ms);
    DefaultHttpClient httpClient = new DefaultHttpClient(params);

    // create post method
    HttpPost postMethod = new HttpPost(LoginServiceUri);

    // create request entity
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(map);
    ByteArrayEntity req_entity = new ByteArrayEntity(baos.toByteArray());
    req_entity.setContentType(MIMETypeConstantsIF.BINARY_TYPE);

    // associating entity with method
    postMethod.setEntity(req_entity);

    // RESPONSE
    httpClient.execute(postMethod, new ResponseHandler<Void>() {
      public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
        HttpEntity resp_entity = response.getEntity();
        if (resp_entity != null) {

          try {
            byte[] data = EntityUtils.toByteArray(resp_entity);
            ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data));
            dataFromServlet = (Hashtable<DataKeys, Serializable>) ois.readObject();
            
            Log.i(getClass().getSimpleName(), "data size from servlet=" + data.toString());
            Log.i(getClass().getSimpleName(), "data hashtable from servlet=" + dataFromServlet.toString());
          }
          catch (Exception e) {
            Log.e(getClass().getSimpleName(), "problem processing post response", e);
          }

        }
        else {
          throw new IOException(
              new StringBuffer()
                  .append("HTTP response : ").append(response.getStatusLine())
                  .toString());
        }
        return null;
      }
    });

  }
  catch (Exception e) {
    ex = e;
//    Log.e(getClass().getSimpleName(), "problem encountered", e);
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    e.printStackTrace(pw);
    Log.e(getClass().getSimpleName(), sw.getBuffer().toString(), e);
  }

  Log.i(getClass().getSimpleName(), "background task - end");
}

/** this method is called in the "edt" */
private void _showInUI() {

  if (data != null)
    Toast.makeText(_activity,
                   "Got data from service: " + data.toString(),
                   Toast.LENGTH_SHORT).show();
  if (ex != null)
    Toast.makeText(_activity,
                   ex.getMessage() == null ? "Error" : "Error - " + ex.getMessage(),
                   Toast.LENGTH_SHORT).show();

//  Toast.makeText(_activity,
//                 "completed background task, rejoining \"edt\"",
//

  _activity._displayUserProfile(dataFromServlet);

}

}//end class GetUserProfile

